package com.org.khtn.gui;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Vector;

import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

public class MyTableSetValue extends AbstractTableModel {

	private Vector colHeaders;
	private Vector tbData;
	public JTable table;

	public MyTableSetValue(Map<String, Map<String, String>> record,
			Map<String, String> field, JTable tb) {
		table = tb;
		colHeaders = new Vector();
		colHeaders.add("");
		tbData = new Vector();
		Vector firstRecord = new Vector();
		firstRecord.add("");
		for (Map.Entry<String, String> e : field.entrySet()) {
			colHeaders.add(e.getKey());
			firstRecord.add("");
		}
		if (record != null) {
			for (Map.Entry<String, Map<String, String>> e : record.entrySet()) {
				Vector dataRow = new Vector();
				Map<String, String> map = e.getValue();
				dataRow.add("");
				for (Map.Entry<String, String> en : map.entrySet()) {
					dataRow.add(en.getValue());
				}
				tbData.add(dataRow);
			}
		} else {
			tbData.add(firstRecord);
		}
	}

	public int getColumnCount() {
		return colHeaders.size();
	}

	public int getRowCount() {
		return tbData.size();
	}

	public String getColumnName(int col) {
		return colHeaders.get(col).toString();
	}

	public Object getValueAt(int row, int column) {
		//System.out.println(getRowCount());
		Vector rowData = (Vector) (tbData.elementAt(row));
		return rowData.elementAt(column);
	}
	
	public void setValueAt(Object value, int row, int col) {
		Vector v = (Vector) tbData.get(row);
		v.set(col, value);
		fireTableCellUpdated(row, col);
	}

	public boolean isCellEditable(int row, int column) {
		if (column == 0) {
			table.setCellSelectionEnabled(false);
			table.setRowSelectionAllowed(true);
			return false;
		}

		table.setRowSelectionAllowed(false);
		table.setCellSelectionEnabled(true);
		return true;
	}


	public void insertNewRowBelow(int row) {
		Vector v = new Vector();
		for (int i = 0; i < getColumnCount(); i++) {
			v.add("");
		}
		tbData.add(row + 1, v);
		fireTableRowsInserted(0, 0);
	}

	public void insertNewRowAbove(int row) {
		Vector v = new Vector();
		for (int i = 0; i < getColumnCount(); i++) {
			v.add("");
		}
		tbData.add(row, v);
		fireTableRowsInserted(getRowCount() - 1, getRowCount() - 1);
	}

	public void deleteRow(int row) {
		if (getRowCount() > 1 && row != -1) {
			if (row != 0) {
				tbData.removeElementAt(row);
				fireTableRowsDeleted(0, 0);
			} else if (row == 0) {
				tbData.removeElementAt(row);
				fireTableRowsDeleted(1, 1);
			}
		}
	}
}